﻿Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.SqlClient
Imports CodeMatrix.Context

Public Class Stp_Department_Hierarchy

    Public Shared Function GetDepartmentByGroupUserCode(ByVal srcTbl As DataTable) As DataTable

        Dim result As String = ""
        Dim groupUserCode As Integer

        For i As Integer = 0 To srcTbl.Rows.Count - 1

            groupUserCode = srcTbl.Rows(i)("group_code")

            ' Get department id
            Dim reTbl = CodeMatrix.Utilities.CodeHelper.GetDataTable( _
                       "select department_code from group_user where group_user_code = " & groupUserCode)

            result = GetParents(reTbl)

            srcTbl.Rows(i)("dept_hirachy") = result

        Next

        Return srcTbl

    End Function

    Public Shared Function GetDepartmentByStaffCode(ByVal srcTbl As DataTable) As DataTable

        Dim result As String = ""
        Dim staffCode As Integer

        For i As Integer = 0 To srcTbl.Rows.Count - 1

            staffCode = srcTbl.Rows(i)("staff_code")

            ' Get department id
            Dim reTbl = CodeMatrix.Utilities.CodeHelper.GetDataTable( _
                       "select department_code from staff where staff_code = " & staffCode)

            result = GetParents(reTbl)

            srcTbl.Rows(i)("department_name") = result

        Next

        Return srcTbl

    End Function

    Private Shared Function GetParents(ByVal reTbl As DataTable) As String

        Dim output As String = ""
        Dim dep_parent As Integer = 0

        Dim departmentcode As Integer = reTbl.Rows(0)(0)

        ' Call first time
        Dim reTblParent = CodeMatrix.Utilities.CodeHelper.GetDataTable( _
                    "select department_parent from stp_department where department_code = " & departmentcode)

        Do While Not (reTblParent.Rows(0)(0) Is DBNull.Value)

            Dim reTblDepartName = CodeMatrix.Utilities.CodeHelper.GetDataTable( _
                    "select department_name from stp_department where department_code = " & reTblParent.Rows(0)(0))

            If (Not String.IsNullOrEmpty(output)) Then

                output = "," & output
                'output = output & ","
            End If

            'top department is in front
            output = reTblDepartName.Rows(0)(0).ToString() & output
            'output = output & reTblParent.Rows(0)(0).ToString()

            ' Get next one
            reTblParent = CodeMatrix.Utilities.CodeHelper.GetDataTable( _
                    "select department_parent from stp_department where department_code = " & reTblParent.Rows(0)(0).ToString())
        Loop

        Return output

    End Function

End Class
